package org.dingfugui.triple.proxy.jdk;

import org.dingfugui.triple.proxy.ProxyFactory;
import org.dingfugui.triple.proxy.ProxyHandler;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by fugui.ding on 2015/6/10.
 */
public class JdkProxyFactory implements ProxyFactory {

    @SuppressWarnings("unchecked")
    @Override
    public <T> T getProxy(final Class<T> cls, final ProxyHandler handler) {

        Object proxy = Proxy.newProxyInstance(cls.getClassLoader(), new Class[]{cls}, (Object target, Method method, Object[] args) -> {
            if (method.getName().equals("toString") && method.getParameterCount() == 0) {
                return cls.toString();
            }
            return handler.invoke(cls, method.getName(), method.getParameterTypes(), args);
        });

        return (T) proxy;

    }
}

